<template>
  <div class="moban">
    <div class="user-head">
      <div class="user-head-l">
        <div class="head-text" style="width:15%">
          创建日期
        </div>
        <div class="head-date">
          <el-date-picker v-model="queryList.startTime" @change="startTimeStatus" :picker-options="pickerOptionsStart" type="date" placeholder="开始日期">
          </el-date-picker>
        </div>
        <div class="head-text">
          至
        </div>
        <div class="head-date">
          <el-date-picker v-model="queryList.endTime" @change="endTimeStatus" :picker-options="pickerOptionsEnd" type="date" placeholder="结束日期">
          </el-date-picker>
        </div>
      </div>
      <div class="user-head-r">
        <div class="head-r-l">
          <div class="head-input">
            <el-input v-model="queryList.queryData" placeholder="名称查询"> </el-input>
          </div>
          <div class="head-button" @click="getSealData(queryList)">
            查询
          </div>
          <div class="head-button" @click="newAdd">
            新增
          </div>
          <div class="">
            <el-select v-model="app_idHome" v-if="showSelect" placeholder="请选择应用类型" @change="getSelectHome(app_idHome)">
              <el-option v-for="item in optionsAppid" :key="item.app_id" :label="item.name" :value="item.app_id"> </el-option>
            </el-select>
          </div>
        </div>
        <div class="head-r-r head-button" @click="exportClick">
          导出
        </div>
      </div>
    </div>
    <div class="moban-list">
      <div class="moban-item" v-for="(item, index) of pageData.tableData" v-loading="loading" :key="index">
        <div class="moban-item-change">
          <div class="Check" v-if="check" @click="changecheck">
            <span></span>
          </div>
          <div class="nocheck" v-else @click="changecheck"></div>
        </div>
        <div class="moban-item-con">
          <div class="item-con-img">
            <el-image :src="item.imgurl" @click="imgPdf(item)" style="position:relative;cursor: pointer;" id="el-img"> </el-image>
          </div>
          <div class="moban-con-text">
            <div class="moban-con-texts">
              <div class="con-text-title">模板名称:</div>
              <div class="con-text-con">{{ item.name }}</div>
            </div>
            <div class="moban-con-texts">
              <div class="con-text-title">模 板 ID:</div>
              <div class="con-text-con">{{ item.template_id }}</div>
            </div>
            <div class="moban-con-texts">
              <div class="con-text-title">创建时间:</div>
              <div class="con-text-con">{{ item.create_time }}</div>
            </div>
          </div>
          <div class="moban-lock" @click="delClick(item)">删除</div>
        </div>
      </div>
      <p v-if="pageData.total == 0" style="text-align: center;width:100%;padding:30px 0;">暂无数据</p>
    </div>

    <div class="page">
      <div class="block">
        <el-pagination
          background
          @size-change="handleSizeChange"
          :pager-count="5"
          @current-change="handleCurrentChange"
          :page-size="pageData.pageSize"
          layout="prev, pager, next, jumper"
          :total="pageData.total"
          :current-page.sync="pageData.currentPage"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 增加的弹框 -->
    <el-dialog title="新增" :visible.sync="dialogFormAdd" id="add">
      <el-form :model="sealUser" ref="sealUser">
        <el-form-item label="用户类型">
          <el-select v-model="sealUser.user_type" clearable placeholder="请选择用户类型">
            <el-option v-for="item in this.userlist" placeholder="请输入用户类型" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用名称">
          <el-select v-model="sealUser.app_id" clearable placeholder="请选择应用名称">
            <el-option v-for="item of optionsAppid" placeholder="请输入应用名称" :key="item.app_id" :label="item.name" :value="item.app_id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户id">
          <el-autocomplete
            type="number"
            popper-class="my-autocomplete"
            :disabled="!sealUser.app_id"
            v-model="state"
            :fetch-suggestions="querySearch"
            placeholder="请输入用户id,个人00开始，企业10开始"
            @select="handleSelect"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.value }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="合同名字">
          <el-input v-model="sealUser.seal_name" placeholder="请输入合同名字" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上传文件" prop="imageUrl">
          <el-upload
            :disabled="!sealUser.app_id"
            :action="this.urlList.urls"
            :limit="1"
            list-type="picture-card"
            accept=".pdf"
            :http-request="ImgClick"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="urlList.dialogVisible">
            <img width="100%" :src="urlList.dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" style="width:120px;padding:10px" @click="AddNewUser">确 认</el-button>
      </div>
    </el-dialog>
    <!-- 删除的弹框 -->
    <el-dialog title="删除" :visible.sync="dialogDel" width="33%" id="del-dialog">
      <span>您确定删除此条合同吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDel = false">取消</el-button>
        <el-button type="primary" @click="dialogDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看的弹框 -->
    <el-dialog title="" class="pdfshow" :visible.sync="pdfshow" width="60%">
      <div id="ppd"></div>
      <i @click="pddIcon" class="el-icon-close pdd-icon"></i>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import pdf from 'pdfobject'
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      srcList: [],
      check: false, //用来判断当前模板是否选中 应该和后台连接起来判断的这里只是作为测试
      queryList: {
        startTime: '', //查询的时候的开始时间
        endTime: '', //查询的时候结束时间
        queryData: '' //查询信息
      },
      dialogFormAdd: false, // 添加状态
      urlList: {
        dialogImageUrl: '',
        dialogVisible: false,
        urls: 'http://192.168.2.174:8087/web/file/upload-file?access_token=' + this.token
      },
      sealUser: {
        // 添加列表
        app_id: '',
        file_id: '',
        name: ''
      },
      applicationList: [], // 应用列表
      sealList: [], // 模板类型列表
      imgId: '', // 上传图片获取Id
      // 用户类型
      userlist: [
        {
          value: '00',
          label: '个人用户'
        },
        {
          value: '10',
          label: '企业用户'
        }
      ],
      state: '', // 用户id
      restaurants: [], // 后台获取的用户id列表
      userTypeId: '', //用户ID
      pageData: {
        tableData: {},
        currentPage: 1, //当前的页数
        pageSize: 6, //每一页存放的数据条数
        total: 0
      },
      dialogDel: false, // 删除合同
      add_id: '', // 当前删除合同的id
      contract_id: '',
      // 刚进页面获取appid
      app_idHome: '',
      optionsAppid: [],
      pdfshow: false,
      httpUrl: 'http://192.168.1.10/api', // 请求头
      // 时间选择器校验
      pickerOptionsStart: {
        disabledDate: time => {
          let endDateVal = this.queryList.endTime
          if (endDateVal) {
            return time.getTime() > new Date(endDateVal).getTime()
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          let beginDateVal = this.queryList.startTime
          if (beginDateVal) {
            return time.getTime() < new Date(beginDateVal).getTime()
          }
        }
      },
      // appid显示与隐藏
      showSelect: false
    }
  },
  methods: {
    // 切换应用
    getSelectHome(val) {
      // console.log(val)
      this.app_idHome = val
      this.getSealData()
    },
    // 时间选择器起始时间校验
    // 时间开始选择器
    startTimeStatus(value) {
      this.queryList.startTime = value
    },
    // 时间结束选择器
    endTimeStatus(value) {
      this.queryList.endTime = value
    },
    // 上传图片的操作
    handleRemove(file, fileList) {
      // 移除图片
      console.log(file, fileList)
    },
    beforeUpload(file) {
      // 上传图片之前
      console.log(file)
      const isJPG = file.type
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    ImgClick(a) {
      const formdata = new FormData()
      formdata.append('file', a.file)
      formdata.append('fileType', 'contract') // 这是传的参数string格式
      formdata.append('appId', this.sealUser.app_id)
      formdata.append('userId', this.state)
      this.axios
        .post(`/web/file/upload-file-api?access_token=${this.token}`, formdata, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        .then(res => {
          console.log(res.data)
          // console.log(res.data.data.data.file_id)
          if (res.data.result_code == '0') {
            this.imgId = res.data.data.data.file_id
            this.$message({
              message: '上传成功！',
              type: 'success'
            })
          } else {
            this.$message({
              message: '上传失败！',
              type: 'error'
            })
          }
        })
    },
    //点击左右跳转页码
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.currentPage = val
      this.getSealData()
    },
    //点击跳转对应的页码
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getSealData()
    },
    //改变选中和未选中
    changecheck() {
      this.check = !this.check
    },
    // 导出Excel
    async exportClick() {
      if (this.app_idHome) {
        window.open(`${this.httpUrl}/web/contract/export_excel?access_token=${this.token}&appId=${this.app_idHome}`)
      } else {
        this.$message({
          message: '暂无数据！',
          type: 'error'
        })
      }
    },
    //获取用户列表信息以及查询功能
    async getSealData(query = {}) {
      // 获取列表数据
      this.loading = true
      // 搜索时，页码需要设置为1，才能正确返回数据，因为数据是从第一页开始返回的
      query ? (this.pageData.currentPage = 1) : ''
      const params = {
        app_id: this.app_idHome,
        page: this.pageData.currentPage,
        size: 6,
        begin_time: query.startTime,
        end_time: query.endTime,
        name: query.queryData
      }
      const nums = JSON.stringify(params)
      const data = await this.http.post(`/web/contract/contract_list?access_token=${this.token}`, nums)
      console.log(data)
      this.loading = false
      if (data.result_code == '0') {
        const res = data.data
        this.pageData.tableData = res.records
        this.pageData.total = res.total
        for (let i in this.pageData.tableData) {
          this.pageData.tableData[
            i
          ].imgurl = `${this.httpUrl}/web/file/examine-file-api?access_token=${this.token}&fileId=${this.pageData.tableData[i].thumbnail}`
          this.srcList.push(this.pageData.tableData[i].imgurl) // 转为数组
          // console.log(typeof this.srcList)
          console.log(this.pageData.tableData[i])
        }
      }
    },
    // 新增用户
    async newAdd() {
      this.addId()
      this.dialogFormAdd = true
      const data = await this.http.get(`/web/seal/impression_type_list?access_token=${this.token}`)
      console.log(data)
      this.sealList = data.data.impression_types
    },
    AddNewUser() {
      const params = {
        app_id: this.sealUser.app_id,
        file_id: this.imgId,
        name: this.sealUser.seal_name,
        user_id: this.state
      }
      const idx = JSON.stringify(params)
      console.log(idx)
      this.http.post(`/web/contract/add?access_token=${this.token}`, idx).then(data => {
        console.log(data)
        if (data.result_code == '0') {
          this.$message({
            message: data.result_message,
            type: 'success'
          })
          this.dialogFormAdd = false
          this.getSealData()
        } else if (data.result_code == '4003') {
          this.$message({
            message: '选项不得为空！',
            type: 'error'
          })
        } else if (data.result_code == '4508') {
          this.$message({
            message: '请上传有效合同！',
            type: 'error'
          })
        }
      })
    },
    // 个人id模糊查询
    async querySearch(queryString, cb) {
      console.log(queryString)
      const idx = {
        app_id: this.sealUser.app_id,
        user_id: queryString,
        user_type: this.sealUser.user_type
      }
      const idxs = JSON.stringify(idx)
      const data = await this.http.post(`/web/app/userId?access_token=${this.token}`, idxs)
      this.restaurants = data.data.user_ids
      var rest = this.restaurants
      var results = queryString ? rest.filter(this.createStateFilter(queryString)) : rest
      console.log(results)
      results.reduce((res, item) => {
        res.push({ value: item })
        return results
      }, [])
      cb(results)
    },
    createStateFilter(queryString) {
      return restaurant => {
        return restaurant.indexOf(queryString) === 0
      }
    },
    handleSelect(item) {
      console.log(item)
    },
    // 合同删除
    delClick(item) {
      this.dialogDel = true
      console.log(item)
      this.add_id = item.app_id
      this.contract_id = item.contract_id
    },
    async dialogDelete() {
      const params = {
        contract_id: this.contract_id,
        app_id: this.add_id
      }
      const nums = JSON.stringify(params)
      console.log(nums)
      const data = await this.http.post(`/web/contract/remove?access_token=${this.token}`, nums)
      console.log(data)
      if (data.result_code == '0') {
        this.$message({
          message: data.result_message,
          type: 'success'
        })
        this.dialogDel = false
        this.getSealData() // 调取应用接口
      } else {
        this.$message({
          message: data.result_message,
          type: 'error'
        })
        this.dialogDel = false
      }
    },
    // 查看pdf
    imgPdf(item) {
      this.pdfshow = true
      this.$nextTick(function() {
        console.log(`${this.httpUrl}/web/file/examine-file-api?access_token=${this.token}&fileId=${item.file_id}`)
        pdf.embed(`${this.httpUrl}/web/file/examine-file-api?access_token=${this.token}&fileId=${item.file_id}`, '#ppd')
      })
    },
    // 关闭pdf
    pddIcon() {
      this.pdfshow = false
    },
    // 获取appid
    async addId() {
      //获取用户Id
      const data = await this.http.get(`/web/app/appId?access_token=${this.token}&userId=${this.userid}`)
      // console.log(data)
      if (data.result_code == '0') {
        this.optionsAppid = data.data.app
        this.app_idHome = this.optionsAppid[0].app_id
        this.getSealData()
        if (this.optionsAppid.length !== 0) {
          this.showSelect = true
        } else {
          this.showSelect = false
        }
      }
    }
  },
  created() {
    this.addId()
  },
  computed: {
    ...mapState({
      userid: modules => modules.login.loginList.developer_id,
      token: modules => modules.login.loginList.token,
      appid: modules => modules.login.appid
    })
  }
}
</script>
<style scoped lang="scss">
.moban {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  .user-head {
    height: 80px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    box-sizing: border-box;
    padding: 0 50px 0 40px;
    .user-head-l {
      width: 40%;
      display: flex;
      align-items: center;
      .head-date {
        width: 35%;
        /deep/.el-input__inner {
          background: rgba(235, 248, 236, 1);
          border-radius: 6px;
          border: 1px solid rgba(35, 183, 105, 1);
          font-size: 18px;
          color: rgba(102, 102, 102, 1);
          letter-spacing: 1px;
        }
        /deep/.el-input__prefix {
          //right: -79%;
          .el-icon-date {
            font-size: 20px;
          }
        }
      }
      .head-text {
        font-size: 18px;
        font-family: NotoSansHans-Regular, NotoSansHans;
        font-weight: 400;
        color: rgba(102, 102, 102, 1);
        letter-spacing: 1px;
        margin: 0 15px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .head-text:nth-child(1) {
        margin-left: 0;
      }
    }
    .user-head-r {
      width: 55%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .head-button {
        width: 100px;
        height: 40px;
        background: rgba(35, 183, 105, 1);
        border-radius: 6px;
        margin: 0 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        cursor: pointer;
      }
      .head-r-l {
        display: flex;
        align-items: center;
        width: 60%;
        .head-input {
          /deep/.el-input__inner {
            background: rgba(235, 248, 236, 1);
            border-radius: 6px;
            border: 1px solid rgba(35, 183, 105, 1);
            font-size: 18px;
            color: rgba(102, 102, 102, 1);
            letter-spacing: 1px;
          }
        }
      }
    }
  }
  .moban-list {
    width: 100%;
    background-color: #fff;
    margin-top: 8px;
    padding: 20px;
    padding-bottom: 0;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    // min-height: 650px;
    // height: 650px;
    .moban-item {
      position: relative;
      display: flex;
      align-items: center;
      height: auto;
      justify-content: space-between;
      width: 49%;
      box-sizing: border-box;
      box-sizing: border-box;
      margin-bottom: 18px;
      .moban-lock {
        position: absolute;
        cursor: pointer;
        top: 20px;
        right: 20px;
        width: 71px;
        height: 28px;
        line-height: 28px;
        border-radius: 6px;
        border: 1px solid red;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        font-family: NotoSansHans-Medium, NotoSansHans;
        font-weight: 500;
        color: red;
        letter-spacing: 1px;
      }
      .moban-lock.moban-locked {
        background: rgba(255, 246, 0, 0.2);
      }
      .moban-item-change {
        .Check {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 18px;
          height: 18px;
          border: 1px solid rgba(151, 151, 151, 1);
          background-color: #d8d8d8;
          overflow: hidden;
          span {
            width: 15px;
            height: 8px;
            border-left: 2px solid #fff;
            border-bottom: 2px solid #fff;
            transform: rotate(-53deg) translate(3px, -1px);
          }
        }
        .nocheck {
          width: 18px;
          height: 18px;
          border: 1px solid rgba(151, 151, 151, 1);
        }
      }
      .moban-item-con {
        position: relative;
        width: 100%;
        flex: 1;
        margin-left: 20px;
        height: 200px;
        border-radius: 6px;
        border: 1px solid rgba(153, 153, 153, 1);
        box-sizing: border-box;
        padding: 27px 30px;
        display: flex;
        align-items: center;
        .item-con-img {
          position: relative;
          width: 120px;
          height: 100%;
        }
        .moban-con-text {
          overflow: hidden;
          flex: 1;
          margin-left: 15px;
          .moban-con-texts {
            width: 100%;
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            font-size: 18px;
            font-family: NotoSansHans-Regular, NotoSansHans;
            font-weight: 400;
            color: rgba(51, 51, 51, 1);
            letter-spacing: 1px;
            .con-text-title {
              width: 90px;
              margin-right: 10px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            .con-text-con {
              flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
          .moban-con-texts:nth-child(3) {
            margin-bottom: 0;
          }
        }
        .moban-con-download {
          position: absolute;
          bottom: 20px;
          right: 30px;
          display: block;
          font-size: 25px;
          color: #e0e0e0;
          font-weight: 600;
          cursor: pointer;
        }
      }
    }
  }
  .page {
    display: flex;
    justify-content: center;
    background-color: #fff;
    padding: 30px 0 15px;
  }
  /deep/.el-pagination.is-background .el-pager li:not(.disabled).active {
    background: #23b769;
    color: #fff;
    border: 1px solid #23b769;
  }
}
/deep/#add {
  .el-dialog {
    width: 35%;
    overflow-y: auto;
  }
  .el-input__inner {
    border: 0;
    background-color: #ebf8ec;
  }
  /deep/.el-dialog__body .el-form-item:nth-child(3) .el-form-item__content .el-input {
    width: 151%;
  }
  .el-dialog__header {
    .el-dialog__headerbtn {
      top: 11px;
      .el-icon-close {
        font-size: 30px;
        font-weight: 600;
        color: #999999;
      }
    }
  }
  .el-dialog__body {
    padding-bottom: 25px;
    .el-form-item {
      .el-select {
        width: 60%;
        .el-input {
          width: 100%;
        }
      }
      .el-form-item__label {
        width: 30%;
        padding-right: 20px;
        font-size: 18px;
        color: rgba(102, 102, 102, 1);
        letter-spacing: 1px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .el-input {
        width: 60%;
        background: rgba(235, 248, 236, 1);
        border-radius: 6px;
        border: 1px solid rgba(35, 183, 105, 1);
        input {
          font-size: 18px;
          color: #333;
          letter-spacing: 1px;
        }
      }
    }
    .el-form-item.phone {
      .el-form-item__content {
        display: flex;
        align-items: center;
        .el-input {
          width: 65%;
        }
        .send {
          width: 16%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-left: 4%;
          cursor: pointer;
          height: 100%;
          background: rgba(35, 183, 105, 1);
          border-radius: 6px;
          font-size: 18px;
          color: rgba(255, 255, 255, 1);
          letter-spacing: 1px;
        }
      }
    }
  }
  .el-dialog__footer {
    text-align: center;
    padding-bottom: 30px;
  }
  /deep/.el-button--primary:hover {
    background: #23b769;
  }
  // 模糊查询
  .my-autocomplete {
    li {
      line-height: normal;
      padding: 7px;

      .name {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .addr {
        font-size: 12px;
        color: #b4b4b4;
      }

      .highlighted .addr {
        color: #ddd;
      }
    }
  }
  // 分页器
  /deep/.el-pagination.is-background .btn-next,
  .el-pagination.is-background .btn-prev,
  .el-pagination.is-background .el-pager li {
    background-color: #ffffff !important;
    color: #999999 !important;
  }
  /deep/.el-image-viewer__canvas {
    margin-top: 5% !important;
    height: 90% !important;
  }
}
//删除应用
/deep/#del-dialog {
  margin: 0 auto;
  margin-top: 20vh;
  .el-dialog__headerbtn {
    top: 11px;
    .el-icon-close {
      font-size: 30px;
      font-weight: 600;
      color: #999999;
    }
  }
  .el-dialog__header {
    height: 60px;
  }
  .el-dialog__body {
    padding: 10%;
    display: flex;
    justify-content: center;
    font-size: 18px;
    font-weight: 400;
    color: rgba(51, 51, 51, 1);
    letter-spacing: 1px;
  }
  .el-dialog__footer {
    padding-bottom: 45px;
    text-align: center;
    .el-button {
      border-radius: 6px;
    }
    .el-button:nth-child(2) {
      margin-left: 40px;
    }
    .el-button--default {
      background: rgba(35, 183, 105, 1);
      color: rgba(255, 255, 255, 1);
    }
    .el-button--primary {
      background: rgba(255, 255, 255, 1);
      color: rgba(35, 183, 105, 1);
      border: 1px solid rgba(35, 183, 105, 1);
    }
  }
}
// 查看弹框
/deep/.pdfshow {
  .el-dialog {
    height: 80%;
    .el-dialog__header {
      display: none;
    }
    .el-dialog__body {
      padding: 0;
      height: 100%;
      #ppd {
        height: 100%;
      }
      .pdd-icon {
        color: #fff;
        font-size: 30px;
        position: absolute;
        top: 0;
        right: -10%;
      }
    }
  }
}
/deep/.el-image {
  border: 1px solid gainsboro;
}
</style>
